//
//  MYGAddCaseFilesViewController.swift
//  MYGrow
//
//  Created by 小火科技 on 2024/4/9.
//

import UIKit
import JXSegmentedView
import BRPickerView


class MYGAddCaseFilesViewController: MYGBaseController {
    var hosArr:[String] = []
    var keshiArr:[String] = []

    var data:MYGCaseSubModel?{
        didSet{
            guard let model = data else{return}
            self.time = model.visit_time
            let info = model.outpatient.info
            if (info != nil){
                self.result =  model.outpatient.info!
            }
            
            let doc = model.outpatient.doctor
            if (doc != nil){
                self.doctor = model.outpatient.doctor!
            }
           
            self.hospital = model.hospital
            if model.outpatient.department != nil {
                self.department = model.outpatient.department!
            }
        }
    }
    
    var model:MYGCaseListFileModel = MYGCaseListFileModel()
    var index:Int = 0 //"门诊", "检验/检查", "用药记录(处方)", "手术","体检"  对应 0到4
    private var tipTitle:String = "上传门诊病历/检查报告"
    
    private var time:String = ""
    private var result:String = ""
    private var hospital:String = ""
    private var department:String = ""
    private var info:String = ""
    private var img:[UIImage] = []
    private var doctor:String = ""

    private var contents:[[String:String]] = []
    
    //定义的数据
    var outpatient:[String:Any] = [:]
    var inspection:[String:Any] = [:]
    var medication:[String:Any] = [:]
    var operation:[String:Any] = [:]
    var examination:[String:Any] = [:]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .rgba(245, 245, 245, 1)
        self.title = "病历夹"
        
        confgUI()
        configDataSource()
        self.view.isUserInteractionEnabled = false
//        getHostpitalList()
//        getHosAndSub()
    }
    
    func confgUI(){
        
        view.addSubview(segmentView)
        segmentView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(48)
            make.top.equalTo(navHeight + statusBarHeight)
        }
    
        view.addSubview(backButton)
        backButton.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-18)
            make.width.equalTo((screenWidth - 39*3)/2)
            make.left.equalTo(39)
            make.height.equalTo(39)
        }
//        view.addSubview(saveButton)
//        saveButton.snp.makeConstraints { make in
//            make.bottom.equalToSuperview().offset(-18)
//            make.width.equalTo((screenWidth - 39*3)/2)
//            make.right.equalToSuperview().offset(-39)
//            make.height.equalTo(39)
//        }
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(15)
            make.top.equalTo(segmentView.snp.bottom)
            make.bottom.equalTo(backButton.snp.top)
        }
        
    }
    
    private lazy var tableView: UITableView = {
        let tableV = UITableView()
        tableV.backgroundColor = .rgba(245, 245, 245, 1)
        tableV.delegate = self
        tableV.dataSource = self
        tableV.separatorStyle = .none
        tableV.showsVerticalScrollIndicator = false
        tableV.isScrollEnabled = false
        tableV.register(cellWithClass: MYGAddCaseFilesTimeCell.self)
        tableV.register(cellWithClass: MYGAddCaseFilesCell.self)
        return tableV
    }()
    
    private lazy var segmentView: JXSegmentedView = {
        let segment = JXSegmentedView()
        segment.delegate = self
        segment.dataSource = dataSource
        segment.defaultSelectedIndex = self.index
        segment.backgroundColor = .rgba(249, 249, 249, 1)
        let indicator = JXSegmentedIndicatorLineView()
        indicator.backgroundColor = .white
        indicator.indicatorHeight = 2
        indicator.indicatorWidth = 44
        indicator.indicatorPosition = .bottom
        
        segment.indicators = [indicator]
        return segment
    }()
    
    private lazy var dataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.titles = ["门诊", "检验/检查", "用药记录(处方)", "手术","体检"]
        dataSource.titleNormalFont = .medium(14)
        dataSource.titleNormalColor = .rgba(153, 153, 153, 1)
        dataSource.titleSelectedFont = .regular(14)
        dataSource.titleSelectedColor = .rgba(255, 0, 0, 1)
        return dataSource
    }()
    
    
    private lazy var backButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("返回", for: .normal)
        btn.setTitleColor(.black, for: .normal)
        btn.backgroundColor = .white
        btn.titleLabel?.font = .regular(16)
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 20
        btn.layer.borderWidth = 1
        btn.layer.borderColor = UIColor.rgba(153, 153, 153, 1).cgColor
        btn.addTarget(self, action: #selector(clickBackBtn), for: .touchUpInside)
        return btn
    }()
    
//    private lazy var saveButton: UIButton = {
//        let btn = UIButton()
//        btn.setTitle("保存", for: .normal)
//        btn.setTitleColor(.white, for: .normal)
//        btn.backgroundColor = .rgba(162, 146, 254, 1)
//        btn.titleLabel?.font = .regular(16)
//        btn.layer.masksToBounds = true
//        btn.layer.cornerRadius = 20
//        btn.addTarget(self, action: #selector(clickSaveButton), for: .touchUpInside)
//        return btn
//    }()
    
}

extension MYGAddCaseFilesViewController:JXSegmentedViewDelegate {
    
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        if(self.index == index) {return}
        self.index = index
        switch index {
        case 0:
            self.tipTitle = "上传门诊病历/检查报告"
        case 1:
            self.tipTitle = "上传检验检查单"
        case 2:
            self.tipTitle = "上传门诊病历/检查报告"
        case 3:
            self.tipTitle = "上传图片(手术相关图片)"
        default:
            break
        }
        
        configDataSource()
    }
    
    
}

extension MYGAddCaseFilesViewController:UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        contents.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 2 {
            return 138
        }
        
        return 54
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = contents[indexPath.row]
        if (indexPath.row == 2 ){
            let cell = tableView.dequeueReusableCell(withClass: MYGAddCaseFilesCell.self, for: indexPath)
            cell.titleLabel.text = model["name"]
            cell.selectImageBlock = {[self] images in
                print(images)
                self.img = images
            }
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withClass: MYGAddCaseFilesTimeCell.self, for: indexPath)
            cell.index = indexPath.row
            cell.data = model
            cell.inputDidChange = { [self] (value,index) in
                print(value,index)
                dataSourceFactory(value: value, index: index)
            }
            if indexPath.row == 3 {
                cell.textFiled.text = hospital
                cell.contentView.isUserInteractionEnabled = false
            }else
            if indexPath.row == 4 {
                cell.textFiled.text = department
                cell.contentView.isUserInteractionEnabled = false
            }else {
                cell.contentView.isUserInteractionEnabled = true

            }
            return cell
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.row {
        case 3:
            BRStringPickerView.showPicker(withTitle: "请选择就诊医院", dataSourceArr: hosArr, select: 0) {[self] item in
//                sexItem.content = item?.value ?? ""
//                self.tableView.reloadData()
                self.dataSourceFactory(value: item?.value ?? "", index: 3)
                self.configDataSource()
            }
            break
        case 4:
            BRStringPickerView.showPicker(withTitle: "请选择就诊科室", dataSourceArr: keshiArr, select: 0) {[self] item in
//                sexItem.content = item?.value ?? ""
//                self.tableView.reloadData()
                self.dataSourceFactory(value: item?.value ?? "", index: 4)
                self.configDataSource()
            }
            break
        default:
            break
        }
    }
}

extension MYGAddCaseFilesViewController {
    func configDataSource(){
        contents.removeAll()
        contents = [["name":"就诊日期","value":self.time],["name":"诊断","value":self.result]
                    ,["name":self.tipTitle,],["name":"就诊医院","value":self.hospital],["name":"就诊科室","value":self.department]
                                  ] //,["name":"医嘱印象","value":self.info]
        if self.index == 0 || self.index == 2 {
            contents.append(["name":"主治医生","value":self.doctor])
        }
        tableView.reloadData()

    }
    
    //获取医院列表
    func getHostpitalList(){
        MMYGNetwork<MYGResumeApi, MYGPageModel<MYGHospitalModel>>.request(target: .hospitals(kwd: "", hosp_type: "", hosp_level: "", address: "",page: 1)) { item in
            MYGLoading.hide()
            guard let item = item else {
                return
            }
            
            for model in item.list  {
                self.hosArr.append(model.hosp_name)
            }
            
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }

    }
    
    func getHosAndSub(){
        
        MYGNetwork<MYGResumeApi, MYGSubjectListModel>.request(target: .getSubjectList(params: [:])) {[weak self] result in
            let arr:[MYGSubjectDetailModel] = result.data ?? []
            for item in arr {
                self?.keshiArr.append(item.label)
            }
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    func dataSourceFactory(value:String,index:Int){
        if (index == 0 ){
            self.time = value
        }else if (index == 1){
            self.result = value
        }else if (index == 3){
            self.hospital = value
        }else if (index == 4){
            self.department = value
        }else if (index == 5){
            self.doctor = value
        }else {
            self.info = value
        }
    }
    
    @objc
    func clickBackBtn(){
        navigationController?.popViewController(animated: true)
    }
    
  //  @objc
//    func clickSaveButton(){
//        
//        if self.department.isEmpty {
//            MMYGHUD.showToast(text: "请输入科室")
//            return
//        }
//        
//        if self.time.isEmpty {
//            MMYGHUD.showToast(text: "请输入时间")
//            return
//        }
//        
//        if self.hospital.isEmpty {
//            MMYGHUD.showToast(text: "请输入就诊医院")
//            return
//        }
//        if (self.index == 0 || self.index == 2 ) && self.doctor.isEmpty {
//            MMYGHUD.showToast(text: "请输入医生")
//            return
//        }
//        
//        guard img.count > 0 else {
//            MMYGHUD.showToast(text: "请选择图片")
//            return
//        }
//        
//        let group = DispatchGroup()
//        var urls: [String] = []
//        var error: String?
//        MYGLoading.show()
//       
//        for image in self.img {
//            group.enter()
//            MMYGNetwork<MYGCommonAPI, MYGEmptyModel>.request(target: .uploadOssFiles(image: image)) { _ in
//            
//            } stringBlock: { text in
//                urls.append(text)
//                group.leave()
//            } failed: { _, err in
//                error = err
//                group.leave()
//            }
//        }
//        
//        group.notify(queue: DispatchQueue.main) { [self] in
//            if let error = error {
//                MYGLoading.hide()
//                MMYGHUD.showToast(text: error)
//                return
//            }
//            MYGLoading.show()
//            
//            switch self.index {
//            case 0:
//                outpatient = ["name":"门诊","img":urls,"department":self.department,"doctor":self.doctor,"hospital":self.hospital,"info":self.result,"time":self.time,"zdTime":self.time]
//            case 1:
//                inspection = ["name":"检验检查","img":urls,"department":self.department,"doctor":self.doctor,"hospital":self.hospital,"info":self.result,"time":self.time,"zdTime":self.time]
//            case 2:
//                medication = ["name":"用药记录","img":urls,"department":self.department,"hospital":self.hospital,"info":self.result,"time":self.time,"zdTime":self.time]
//            case 3:
//                operation = ["name":"手术","img":urls,"department":self.department,"doctor":self.doctor,"hospital":self.hospital,"info":self.result,"time":self.time,"zdTime":self.time]
//            case 4:
//                examination = ["name":"体检","img":urls,"department":self.department,"doctor":self.doctor,"hospital":self.hospital,"info":self.result,"time":self.time,"zdTime":self.time]
//
//            default:
//                break
//            }
//            
//            let patient_id:Int = 0
//            let id:String = (model.id != 0) ? "\(model.id)" : ""
//            
//            MYGNetwork<MYGCaseFilesApi,MYGEmptyModel>.request(target: .addCaseFile(patient_id: "\(patient_id)", hospital: self.hospital, visit_time: self.time,outpatient: outpatient.string!, inspection: inspection.string!,
//                                                                                   medication: medication.string!,
//                                                                                   operation: operation.string!,
//                                                                                   examination: examination.string!,id:id
//                                                                                   )) { _ in
//
////            MYGNetwork<MYGCaseFilesApi,MYGEmptyModel>.request(target: .addCaseFile(params: params)) { _ in
//                MYGLoading.hide()
//                MMYGHUD.showToast(text: "新增成功")
//                NotificationCenter.default.post(name: NSNotification.Name.init("getCaseFileData"), object:nil)
//
//                UIViewController.currentViewController?.navigationController?.popViewController(animated: true)
//
//            } failed: { _, error in
//                MYGLoading.hide()
//                MMYGHUD.showToast(text: error)
//            }
//            
//        }
//        
//    }
    
    
}

